import { Body, Inject, Post, Get } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { OrderShopEntity } from '../../entity/shop';
import { OrderRefundEntity } from '../../entity/refund';
import { OrderRefundService } from '../../service/refund';
import { OrderGoodsEntity } from '../../entity/goods';
import { OrderOrderEntity } from '../../entity/order';

/**
 * 退货单信息
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: OrderRefundEntity,
  service: OrderRefundService,
  pageQueryOp: {
    keyWordLikeFields: ['a.refundNo'],
    fieldEq: ['a.id', 'a.refundStatus', 'a.refundType', 'a.shopId'],
    select: ['a.*', 's.name as shopName'],
    // join: [
    //   {
    //     entity: OrderGoodsEntity,
    //     alias: 'g',
    //     condition: 'a.goodsId = g.id',
    //     type: 'leftJoin',
    //   },
    // ],
    join: [
      {
        entity: OrderShopEntity,
        alias: 's',
        condition: 'a.shopId = s.id',
        type: 'leftJoin',
      },
      // {
      //   entity: OrderOrderEntity,
      //   alias: 'o',
      //   condition: 'a.refundNo = o.orderNo',
      //   type: 'innerJoin',
      // },
    ],
    where: async ctx => {
      const { userPhone, userNickName, shopCityId, isAgent } = ctx.request.body;
      const where = [];

      // where.push(['a.cityId = :shopCityId', { shopCityId }]);

      return where;
    },
    extend: find => {
      find.groupBy('a.id'); // 按订单ID分组，以便聚合商品名称
      return find;
    },
  },
})
export class AdminOrderRefundController extends BaseController {
  @Inject()
  orderRefundService: OrderRefundService;

  // 提交售后/换货订单
  @Post('/submitRefundExchange')
  async submitRefundExchange(
    @Body()
    body: {
      orderId: number;
      refundType: number;
      refundReason: string;
      reasonRemark: string;
    }
  ) {
    const res = await this.orderRefundService.submitRefundExchange(body);
    console.log(res);
    return this.ok(res);
  }

  // 根据orderId查询订单售后/换货信息
  @Post('/getRefundInfoById')
  async getRefundInfoById(@Body() body: { orderId: number }) {
    const res = await this.orderRefundService.getRefundInfoById(body.orderId);
    console.log(res);
    return this.ok(res);
  }

  // 根据orderId查询订单售后/换货信息
  @Post('/getRefundInfoByIdV2')
  async getRefundInfoByIdV2(@Body() body: { orderId: number }) {
    const res = await this.orderRefundService.getRefundInfoByIdV2(body.orderId);
    console.log(res);
    return this.ok(res);
  }

  // 审核售后/换货订单
  @Post('/auditRefundExchange')
  async auditRefundExchange(
    @Body()
    body: {
      auditStatus: number;
    }
  ) {
    const res = await this.orderRefundService.auditRefundExchange(body);
    console.log(res);
    return this.ok(res);
  }
}
